package com.netty.source;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;
import java.util.Arrays;

public class ClientStart {

    private final Bootstrap bootstrap;
    private ChannelHandler[] handlers;

    public ClientStart() {
        this.bootstrap = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class);
    }

    public ClientStart(ChannelHandler... handlers) {
        this();
        this.handlers = handlers;
    }

    public void doStart() {
        bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new LoggingHandler());
                if (handlers != null && handlers.length > 0) {
                    Arrays.stream(handlers).forEach(pipeline::addLast);
                }
            }
        });
        ChannelFuture connect = bootstrap.connect(new InetSocketAddress(8000));
        this.stop(connect);
    }

    public void stop(ChannelFuture channelFuture) {
        try {
            channelFuture.sync().channel().closeFuture();
        } catch (InterruptedException e) {
            throw new RuntimeException("channel 关闭成功");
        }
    }
}
